/*
 * Package il.ac.biu.cs.grossmm.impl.activeData
 * File SqlInnerMapping.java
 * 
 * This is a part of presence service framework prototype. 
 * See javadoc for more information.
 *  
 * Copyright (C) 2006 Grossmann Mark
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package il.ac.biu.cs.grossmm.impl.activeData;

import il.ac.biu.cs.grossmm.api.OperationFailedException;
import il.ac.biu.cs.grossmm.api.data.NodeType;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;

public class SqlInnerMapping extends SqlMapping {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(SqlInnerMapping.class);

	final SqlMapping parentMapping;

	final int parentIndex;

	PreparedStatement insert;

	PreparedStatement delete;

	PreparedStatement selectIds;

	SqlInnerMapping(SqlMapping parentMapping, Connection connection,
			String tableNameBase, NodeType nodeType, int parentIndex,
			Counter counter) throws SQLException {
		super(connection, tableNameBase, nodeType, counter);

		this.parentMapping = parentMapping;
		this.parentIndex = parentIndex;
	}

	void prepare(Cache<SqlNodeBase, Object[]> valuesCache,
			Cache<SqlNodeSet, Set<SqlInnerNode>> subnodesCache)
			throws SQLException {
		super.prepare(valuesCache, subnodesCache);
		for (SqlInnerMapping sim : nodeSetMaps)
			sim.prepare(valuesCache, subnodesCache);

		// //////////// selectIds
		// SELECT id FROM <table> WHERE is_visible AND par_id=?

		StringBuffer sb = new StringBuffer("SELECT id FROM ");
		sb.append(tableName);
		sb.append(" WHERE is_visible AND par_id=?");

		selectIds = connection.prepareStatement(sb.toString());

		// //////////// insert
		// INSERT INTO <table> (is_visible, par_id)
		// VALUES (false, ?)

		sb.setLength(0);
		sb.append("INSERT INTO ").append(tableName);
		sb.append(" (is_visible, par_id) VALUES (false, ?)");

		insert = connection.prepareStatement(sb.toString());

		// //////////// delete
		// DELETE FROM <table> WHERE id=?

		sb.setLength(0);
		sb.append("DELETE FROM ").append(tableName).append(" WHERE id=?");

		delete = connection.prepareStatement(sb.toString());
	}

	/**
	 * Create tables to serialize subnodes data. Note that no commit is issued
	 * within this method.
	 * 
	 * @throws Exception
	 */
	void createTables() throws Exception {
		if (logger.isDebugEnabled()) {
			logger.debug("createSubtables() - start");
		}

		StringBuffer sb = new StringBuffer();

		sb.append("CREATE TABLE ");
		sb.append(tableName);
		sb.append(" (id INTEGER IDENTITY, par_id INTEGER, is_visible BOOLEAN");

		insertFieldDefinitions(sb, propertyMaps);

		sb.append(')');

		String sqlCreateNodes = sb.toString();

		try {
			update("DROP TABLE " + tableName + " IF EXISTS");
			update(sqlCreateNodes);
			update("CREATE INDEX idx_" + tableName + " ON " + tableName
					+ " (par_id)");
		} catch (SQLException e) {
			logger.error(e);
			throw new Exception(
					"Could not create publication point (data sub-nodes tables)");
		}

		SqlInnerMapping[] subMaps = nodeSetMaps;

		for (int i = 0; i < subMaps.length; i++) {
			SqlInnerMapping subMap = subMaps[i];
			subMap.createTables();
		}

		if (logger.isDebugEnabled()) {
			logger.debug("createSubtables() - end");
		}
	}

	public void dropTables() throws SQLException {
		update("DROP TABLE " + tableName + " IF EXISTS");
	}

	public synchronized SqlInnerNode create(SqlNodeBase parent)
			throws SQLException, OperationFailedException {
		insert.setInt(1, parent.id);

		insert.executeUpdate();

		// ResultSet rs = insert.executeQuery("CALL IDENTITY()");
		ResultSet rs = getLastId.executeQuery();
		rs.next();
		int id = rs.getInt(1);

		subnodesCache.update(new SqlNodeSet(parent, parentIndex));

		return new SqlInnerNode(parent, this, id);
	}

	public void delete(SqlInnerNode node) throws SQLException {
		delete.setInt(1, node.id);

		delete.executeUpdate();

		// TODO delete subnodes (manually or ensure cascading)
	}

	/**
	 * Queries for all child nodes of given parent within this mapping. Cache is
	 * not used.
	 * 
	 * @param parent
	 *            the parent node
	 * @return set of all child nodes of given parent within this mapping
	 * @throws SQLException
	 */
	Set<SqlInnerNode> childrenOf(SqlNodeBase parent) throws SQLException {
		selectIds.setInt(1, parent.id);
		ResultSet rs = selectIds.executeQuery();

		HashSet<SqlInnerNode> set = new HashSet<SqlInnerNode>();

		while (rs.next()) {
			int id = rs.getInt(1);
			SqlInnerNode node = new SqlInnerNode(parent, this, id);
			set.add(node);
		}

		return set;
	}

}
